package com.dongdongshop.aliyun;

import cn.hutool.core.util.RandomUtil;
import com.aliyun.dysmsapi20170525.models.*;
import com.aliyun.teaopenapi.models.*;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

@Component
@RocketMQMessageListener(topic = "dongdongshop-sms-topic",consumerGroup = "dongdongshop_sms_service")
public class Sample implements RocketMQListener<String> {

    @Resource
    private RedisTemplate redisTemplate;

    /**
     * 使用AK&SK初始化账号Client
     * @param accessKeyId
     * @param accessKeySecret
     * @return Client
     * @throws Exception
     */
    public static com.aliyun.dysmsapi20170525.Client createClient(String accessKeyId, String accessKeySecret) throws Exception {
        Config config = new Config()
                // 您的AccessKey ID
                .setAccessKeyId(accessKeyId)
                // 您的AccessKey Secret
                .setAccessKeySecret(accessKeySecret);
        // 访问的域名
        config.endpoint = "dysmsapi.aliyuncs.com";
        return new com.aliyun.dysmsapi20170525.Client(config);
    }

    @Override
    public void onMessage(String phone) {
        try {
            com.aliyun.dysmsapi20170525.Client client = Sample.createClient("LTAI4GCbdwnjCGwQj9Z3tr3N", "27ih4pc1W1tqey9X4mmCy1JUotAX7L");
            String i = RandomUtil.randomNumbers(4);
            redisTemplate.boundValueOps(phone).set(i);
            redisTemplate.boundValueOps(phone).expire(1, TimeUnit.MINUTES);
            SendSmsRequest sendSmsRequest = new SendSmsRequest()
                    .setPhoneNumbers(phone)
                    .setSignName("东科创想")
                    .setTemplateCode("SMS_162522027")
                    .setTemplateParam("{\"sms_code\":\""+ i +"\"}");
            // 复制代码运行请自行打印 API 的返回值
            client.sendSms(sendSmsRequest);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
}
